package com.example.auth;

import com.example.auth.utils.JwtUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SecurityApplication {

	private final AuthenticationManagerBuilder authenticationManagerBuilder;

	public SecurityApplication(AuthenticationManagerBuilder authenticationManagerBuilder) {
		this.authenticationManagerBuilder = authenticationManagerBuilder;
	}

	public static void main(String[] args) {
		SpringApplication.run(SecurityApplication.class, args);
	}

	@GetMapping("/")
	public String index(){
		return "security jwt";
	}

	@PostMapping("/login")
	public String login(@RequestParam String username, @RequestParam String password){
		// 登陆验证
		UsernamePasswordAuthenticationToken token =
				new UsernamePasswordAuthenticationToken(username, password);
		Authentication authentication = authenticationManagerBuilder.getObject().authenticate(token);
		SecurityContextHolder.getContext().setAuthentication(authentication);
		//创建jwt信息
		return JwtUtils.createToken(username,"admin");
	}

	@GetMapping("/role/admin")
	@PreAuthorize("hasAnyAuthority('admin')")
	public String roleInfo(){
		return "admin身份校验成功";
	}

	@GetMapping("/role/user")
	@PreAuthorize("hasAnyAuthority('user')")
	public String rolekdream(){
		return "user身份校验成功";
	}

}
